-module(object).
-export([hittest/2]).
-export([new/0, new/2]).
-export([get_faces/1, add_face/2]).
-export([get_box/1, set_box/2]).

-record(object, {
        faces=[],
        box
      }).

hittest(Ray, Object) ->
    case bbox:hittest(Ray, Object#object.box) of
        true -> hittest_faces(Ray, Object#object.faces, []);
        false -> false
    end.

hittest_faces(_Ray, [], []) -> false;
hittest_faces(_Ray, [], Hits) -> hd(lists:keysort(1, Hits));
hittest_faces(Ray, [Face|Tail], Hits) ->
    case face:hittest(Ray, Face) of
        false -> hittest_faces(Ray, Tail, Hits);
        HitFace -> hittest_faces(Ray, Tail, [HitFace | Hits])
    end.

new() -> #object{}.
new(Faces, Box) -> #object{faces=Faces, box=Box}.

get_faces(Object) -> Object#object.faces.
add_face(Face, Object) -> Object#object{faces=[Face|Object#object.faces]}.

get_box(Object) -> Object#object.box.
set_box(Box, Object) -> Object#object{box=Box}.